package com.scu.bank.web;

import com.scu.bank.core.jo.Result;
import com.scu.bank.core.jo.ResultGenerator;
import com.scu.bank.model.pojo.AttachFile;
import com.scu.bank.service.AttachFileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@RestController
@RequestMapping("/file")
public class FileUploadController {

    @Autowired
    private AttachFileService attachFileService;

    @Value(value="${upload.path:#{'D:/upload/'}}")
    private String fileSavePath;

    @PostMapping("/upload")
    @ResponseBody
    public Result upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResultGenerator.genFailResult("上传失败，请选择文件");
        }
        return ResultGenerator.genSuccessResult("上传成功").setData(attachFileService.saveFileToDB(file));
    }

    @GetMapping("/getFileName")
    @ResponseBody
    public Result getFileName(@RequestParam("fileCode") String fileCode){
      String fileName = attachFileService.getFileName(fileCode);
      return ResultGenerator.genSuccessResult(fileName);
    }

//    @GetMapping("/download/{fileCode}")
    @GetMapping("/download")
    public String download(@RequestParam String fileCode,HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        AttachFile attachFile = attachFileService.getFileByCode(fileCode);
        if (attachFile != null){
            File file = new File(fileSavePath,attachFile.getFileCode());
            if (file.exists()){
                response.setContentType("application/force-download");
                response.addHeader("Content-Disposition","attachment;fileName=\""+
                        new String((attachFile.getFileName()).getBytes("utf-8"),"ISO8859-1")+"\"");
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try{
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while(i != -1){
                        os.write(buffer,0,i);
                        i = bis.read(buffer);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    if (bis != null){
                        try{
                            bis.close();
                        }catch (IOException e){
                            e.printStackTrace();
                        }
                    }
                    if (fis != null){
                        try{
                            fis.close();
                        }catch (IOException e){
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return attachFile.getFileName();
    }
}
